import React, { useEffect, useRef, useState } from 'react';
import {
  Breadcrumb,
  Button,
  Card,
  DatePicker,
  Form,
  message,
  Modal,
  Radio,
  Select,
  Space,
  Table,
  Tag,
} from 'antd';
import { EditOutlined, DeleteOutlined } from '@ant-design/icons';
import { Link } from 'react-router-dom';
import { getChannelsApi } from 'api/channel';
import { getArticlesApi, delArticleApi } from 'api/article';
import imgSrc from 'assets/error.png';
import history from 'utils/history';

const { RangePicker } = DatePicker;
const { Option } = Select;
const { confirm } = Modal;

export default function ArticleList() {
  const [dataSource, setDataSource] = useState({});
  const formDataRef = useRef();
  const pageRef = useRef();
  const onFinish = async (values) => {
    let formData = { ...values };
    // console.log(formData);
    if (formData.status === -1) {
      delete formData.status;
    }
    if (formData.date) {
      //选择时间时，从起始的0点开始，结束为当天的23：59点
      const begin_pubdate = formData.date[0]
        .startOf('day')
        .format('YYYY-MM-DD HH:mm:ss');
      const end_pubdate = formData.date[1]
        .endOf('day')
        .format('YYYY-MM-DD HH:mm:ss');
      delete formData.date;
      formData.begin_pubdate = begin_pubdate;
      formData.end_pubdate = end_pubdate;
    }
    console.log(formData);
    //通过json转换一次后，会将值为undefined的键删除
    formData = JSON.parse(JSON.stringify(formData));
    //筛选
    formDataRef.current = formData;
    getArticles(formData);
  };
  const [channels, setChannels] = useState([]);
  //获取频道
  const getChannels = async () => {
    const res = await getChannelsApi();
    setChannels(res.data.channels);
  };
  //获取文章列表
  const getArticles = async (params) => {
    const res = await getArticlesApi(params);
    console.log(45, res);
    setDataSource(res.data);
    pageRef.current = { page: res.data.page, per_page: res.data.per_page };
  };
  //切换分页
  const handlePageChange = (page, per_page) => {
    const formData = formDataRef.current || {};
    // console.log(page, pageSize);
    pageRef.current = { page, per_page };
    getArticles({ ...pageRef.current, ...formData });
  };

  //删除文章
  const handleDel = async (id) => {
    confirm({
      title: '提示',
      content: '是否确认删除？',
      onOk: () => {
        delArticle();
      },
    });
    const delArticle = async () => {
      //判断是否是当页最后一条，是的话就请求上一页的数据
      if (
        pageRef.current.page > 1 &&
        (dataSource.total_count - 1) / dataSource.per_page ===
          dataSource.page - 1
      ) {
        pageRef.current.page -= 1;
      }
      const res = await delArticleApi(id);
      const pageConfig = pageRef.current || {};
      if (res.message === 'OK') {
        message.success('删除成功', 1);
        getArticles({ ...pageConfig, ...formDataRef.current });
      }
    };
  };
  //编辑
  const handleEdit = (id) => {
    console.log(id);
    history.push('/edit/' + id);
  };
  useEffect(() => {
    getChannels();
    getArticles();
  }, []);

  const columns = [
    {
      title: '封面',
      dataIndex: 'cover',
      key: 'cover',
      render(value) {
        return (
          <>
            <img
              src={value.images.length !== 0 ? value.images[0] : imgSrc}
              alt=""
              style={{ width: 100, height: 60, objectFit: 'cover' }}
            />
          </>
        );
      },
    },
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render(value) {
        console.log(666);
        //策略模式
        const arr1 = ['草稿', '待审核', '审核通过', '审核失败'];
        const arr2 = ['lime', 'blue', 'green', 'red'];
        return (
          <>
            <Tag color={arr2[value]}>{arr1[value]}</Tag>
          </>
        );
      },
    },
    {
      title: '发布时间',
      dataIndex: 'pubdate',
      key: 'pubdate',
    },
    {
      title: '阅读数',
      dataIndex: 'read_count',
      key: 'read_count',
    },
    {
      title: '评论数',
      dataIndex: 'comment_count',
      key: 'comment_count',
    },
    {
      title: '点赞数',
      dataIndex: 'like_count',
      key: 'like_count',
    },
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      render(value, record) {
        // console.log(record.id);
        return (
          <>
            <Space>
              <Button
                type="primary"
                shape="circle"
                icon={<EditOutlined style={{ color: '#fff' }} />}
                onClick={() => handleEdit(record.id)}
              ></Button>
              <Button
                type="danger"
                ghost
                shape="circle"
                onClick={() => {
                  handleDel(record.id);
                }}
                icon={<DeleteOutlined style={{ color: '#f00' }} />}
              />
            </Space>
          </>
        );
      },
    },
  ];
  return (
    <div style={{ height: 'calc(100vh-64px-48px)', overflow: 'auto' }}>
      <Card
        title={
          <Breadcrumb>
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>内容管理</Breadcrumb.Item>
          </Breadcrumb>
        }
        bordered={false}
      >
        <Form
          onFinish={onFinish}
          autoComplete="off"
          initialValues={{ status: -1 }}
        >
          <Form.Item label="状态" name="status">
            <Radio.Group>
              <Radio value={-1}>全部</Radio>
              <Radio value={0}>草稿</Radio>
              <Radio value={1}>待审核</Radio>
              <Radio value={2}>审核通过</Radio>
              <Radio value={3}>审核失败</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item label="频道：" name="channel_id">
            <Select style={{ width: 200 }}>
              {channels.map((item) => (
                <Option key={item.id} value={item.id}>
                  {item.name}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item label="日期：" name="date">
            <RangePicker></RangePicker>
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              筛选
            </Button>
          </Form.Item>
        </Form>
        <p>根据筛选条件查询到{dataSource.total_count}条结果：</p>
        <Table
          dataSource={dataSource.results}
          columns={columns}
          rowKey="id"
          pagination={{
            position: ['bottomCenter'],
            total: dataSource.total_count,
            current: dataSource.page,
            pageSize: dataSource.per_page,
            onChange: handlePageChange,
          }}
        />
      </Card>
    </div>
  );
}
